﻿using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;

namespace WinControls
{
    public partial class LogBox : UserControl
    {
        private int stickyCount;
        private bool isMultiline = true;

        public enum LineType { Normal, Sticky }

        public LogBox ()
        {
            InitializeComponent();
        }


        [Category ("Behavior"), Description ("Allow more than 1 non-sticky")]
        public bool IsMultiline
        {
            get { return isMultiline; }
            set
            {
                if (isMultiline != value)
                {
                    isMultiline = value;
                    if (!isMultiline)
                    {
                        stickyCount = 0;
                        lineListBox.Items.Clear();
                    }
                }
            }
        }


        public void AddMessage (string message, LineType strength)
        {
            if (! isMultiline)
                while (stickyCount < lineListBox.Items.Count)
                    lineListBox.Items.RemoveAt (stickyCount);

            lineListBox.Items.Add (message);

            if (! isMultiline && strength == LineType.Sticky)
                ++stickyCount;
        }


        public void ScrollLastIntoView ()
        {
            int visibleItemsCount = lineListBox.ClientSize.Height / lineListBox.ItemHeight;
            lineListBox.TopIndex = Math.Max (lineListBox.Items.Count - visibleItemsCount + 1, 0);
        }


        private void lineListBox_KeyDown (object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                if (e.KeyCode == Keys.A)
                {
                    for (int ii = 0; ii < lineListBox.Items.Count; ++ii)
                        lineListBox.SetSelected (ii, true);
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)
                {
                    var builder = new StringBuilder();
                    foreach (var textLine in lineListBox.SelectedItems)
                        builder.AppendLine (textLine.ToString());

                    DataObject cbData = new DataObject (DataFormats.Text, builder.ToString());
                    Clipboard.SetDataObject (cbData);
                    e.SuppressKeyPress = true;
                }
            }
        }
    }
}
